<?php

namespace addons\qiniu\util;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


/**
 * 七牛云上传
 */
class Qiniuoss{

    protected static $instance;
    protected $config = [];
    protected function __construct()
    {
        $this->config = get_addons_config_format('qiniu');
    }
    public static function instance(){
        if(is_null(self::$instance)){
            self::$instance=new static();
        }
        return self::$instance;
    }
    /**
     * 上传
     */
    public function upload($filename,$filePath){
          // 构建鉴权对象
        try {
          $auth = new Auth($this->config['accessKey'], $this->config['secretKey']);
          $token = $auth->uploadToken($this->config['bucket']);
          $uploadMgr = new UploadManager();
          list($res, $error) = $uploadMgr->putFile($token, $filename, $filePath);
          if($error == null){ //上传成功
              return ['msg'=>'上传成功','url'=>$this->config['domain'].'/'.$res['key']];
          }else{//上传失败
            return ['msg'=>'上传失败','url'=>""];
          }
        } catch (\Exception $e) {
            return ['msg'=>$e->getMessage(),'url'=>""];
        }
    }

}